package com.laboratory.redis;

import com.laboratory.thread.TaskEngine;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * Created by admin on 2019/04/22.
 */
public class RedisJava {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
//        testRedis();
        testgetKey();
    }
    public static final Jedis jedis = new Jedis("localhost");
    public static volatile int a = 1;
    public static void testRedis(){
        //连接本地的 Redis 服务
        Jedis jedis = new Jedis("localhost");
        System.out.println("连接成功");
        //查看服务是否运行
        System.out.println("服务正在运行: "+jedis.ping());
        String myvalue =  jedis.get("mykey");
        System.out.println(myvalue);
        Long index = jedis.incr("index");
        System.out.println(index);

        String filed1 = jedis.hget("myhash", "filed1");
        System.out.println(filed1);

        Set<String> keys =   jedis.keys("*");
        Iterator<String> iterator = keys.iterator();
        while (iterator.hasNext()){
            String key = iterator.next();
            System.out.println(key+ " : "  );
        }

    }
    public static  void testgetKey() throws ExecutionException, InterruptedException {

        List<Future> futures = new ArrayList<>();
        for (int i= 0; i<20; i++) {
            Future future = TaskEngine.getInstance().submit(new Callable() {
                @Override
                public Object call() throws Exception {
                    Jedis jJedis = new Jedis("localhost");
                    String myindex =  jJedis.incr("index").toString();
                    System.out.println(  ++ a);
                    jJedis.close();
                    return myindex;
                }
            });
            futures.add(future);
        }
        for (Future fut:futures) {
            Object index =  fut.get();
            System.out.println(index);
        }


    }

}
